<template>
  <div class="my-box">
    <el-form ref="lscFormRef" :model="form" :rules="rules" label-width="120px" class="my-form">
      <el-form-item label-width="0">
        <span style="font-size: 25px;font-weight: bold">数据预处理配置</span>
      </el-form-item>
      <el-form-item label="所选数据：" class="item">
        <el-input v-model="dataSelect" disabled />
      </el-form-item>
      <el-form-item label="预处理类型：" class="item">
        <el-checkbox border>自定义</el-checkbox>
        <el-button style="margin-left: 10px" type="info">选择已有</el-button>
        <el-button style="margin-left: 10px" type="success">导入策略（pdf/xlsx）</el-button>
      </el-form-item>
      <el-form-item label="最大循环数：" prop="maxRul">
        <el-input :disabled="ifAllCircle" v-model="form.maxRul" placeholder="输入最大循环数（MAX RUL）" style="max-width: 520px" />
        <el-checkbox border style="margin-left: 10px" @change="handleAllCircle">选择完整周期</el-checkbox>
      </el-form-item>
      <el-form-item label="滑动窗口：" class="item" prop="slideWindow">
        <el-input v-model="form.slideWindow" placeholder="滑动窗口大小（slide window size）" style="max-width: 250px" />
        <el-input v-model="form.stride" placeholder="滑动窗口间隔（slide window stride）" style="max-width: 250px;margin-left: 10px" />
        <el-select v-model="form.slideType" placeholder="数据截断策略" style="margin-left: 10px">
          <el-option v-for="dict in lsc_pdata_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="标准化类型：" class="item" prop="normalType">
        <el-select v-model="form.normalType" placeholder="选择数据归一化类型" style="width: 520px">
          <el-option v-for="dict in lsc_normal_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="标准化基准：" class="item" prop="normalBase">
        <el-select v-model="form.normalBase" placeholder="基于本数据集" style="width: 520px" clearable>
          <el-option v-for="dict in dataDict.value" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="验证集划分：" class="item" prop="spilt">
        <el-input v-model="startPop" style="width: 80px;margin-right: 2px" placeholder="开始比例" :disabled="ifAllPop"></el-input>-
        <el-input v-model="endPop" style="width: 80px;margin-left: 2px" placeholder="结束比例" :disabled="ifAllPop"></el-input>
        <el-checkbox border style="margin-left: 10px" @change="noPop">不划分验证集</el-checkbox>
      </el-form-item>
    </el-form>
    <div class="my-form" style="margin-top: 10px">
      <span style="font-size: 25px;font-weight: bold">数据预处理操作</span>
      <div style="margin-top: 10px">
        <el-button type="primary" @click="submitForm">开始预处理</el-button>
        <el-button type="danger" @click="stopProcessing">终止预处理</el-button>
        <el-button type="info">导出配置文件</el-button>
        <el-button type="warning">导出预处理数据</el-button>
      </div>
      <div class="progress-container">
        <span>预处理进度：</span>
        <el-progress
          style="width: 700px;"
          :text-inside="true"
          :percentage="progress"
          :stroke-width="30"
          status="success"
          :striped="striped"
          :striped-flow="stripedFlow"
        ></el-progress>
      </div>
    </div>
  </div>
</template>

<script setup name="Lsc" lang="ts">

import { getLsc, listLsc, updateStatus } from "@/api/lsc/dataset";
import { LscForm, LscQuery } from "@/api/lsc/preprocess/types";
import { addLsc, updateLsc } from "@/api/lsc/preprocess";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { lsc_data_type, lsc_pdata_type, lsc_normal_type } = toRefs<any>(proxy?.useDict('lsc_data_type', 'lsc_pdata_type', 'lsc_normal_type'));

const dataId = ref("");
const dataSelect = ref("")
const startPop = ref("")
const endPop = ref("")
const ifAllPop = ref(false)
const ifAllCircle = ref(false)

const initFormData: LscForm = {
  id: undefined,
  maxRul: undefined,
  slideWindow: undefined,
  stride: undefined,
  slideType: undefined,
  normalType: undefined,
  normalBase: undefined,
  spilt: undefined,
}
const progress = ref(0);
const striped = ref(false);
const stripedFlow = ref(false);
// eslint-disable-next-line no-undef
let interval: NodeJS.Timeout;

const data = reactive<PageData<LscForm, LscQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    maxRul: undefined,
    slideWindow: undefined,
    stride: undefined,
    slideType: undefined,
    normalType: undefined,
    normalBase: undefined,
    spilt: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "不能为空", trigger: "blur" }
    ],
    maxRul: [
      { required: true, message: "最大循环数不能为空", trigger: "blur" }
    ],
    slideWindow: [
      { required: true, message: "滑动窗口数不能为空", trigger: "blur" }
    ],
    stride: [
      { required: true, message: "滑动窗口间隔不能为空", trigger: "blur" }
    ],
    slideType: [
      { required: true, message: "数据断绝策略不能为空", trigger: "change" }
    ],
    normalType: [
      { required: true, message: "标准化类型不能为空", trigger: "change" }
    ],
    normalBase: [
      { required: true, message: "标准化基准不能为空", trigger: "blur" }
    ],
    spilt: [
      { required: true, message: "验证集划分不能为空", trigger: "blur" }
    ],
  }
});
const { queryParams, form, rules } = toRefs(data);

/*组件创建时运行*/
onMounted(() => {
  init();
})
/*初始化方法*/
const init = () => {
  getDataInfo();
  getList()
}

const startProcessing = () => {
  striped.value = true;
  stripedFlow.value = true;

  // 模拟处理进度
  interval = setInterval(() => {
    progress.value += 10;
    if (progress.value >= 100) {
      clearInterval(interval);
      striped.value = false;
      stripedFlow.value = false;
    }
  }, 500);
};

const stopProcessing = () => {
  clearInterval(interval);
  striped.value = false;
  stripedFlow.value = false;
  progress.value = 0;
};

// 监听进度的变化并相应地更新UI
watch(progress, (newProgress) => {
  if (newProgress >= 100) {
    striped.value = false;
    stripedFlow.value = false;
  }
});

interface DataDict {
  value: { label: string; value: string | number }[];
}

const dataDict: DataDict = {
  value: [{label: "本数据集", value: "0"}]
};

const getList = async () => {
  const res = await listLsc(Object.assign({ status: 1 }));
  res.rows.forEach(item => dataDict.value.push({label: item.dataName, value: item.id}))
  console.log('res', dataDict)
}
const noPop = () => {
  ifAllPop.value = !ifAllPop.value;
  if (ifAllPop.value) {
    form.value.spilt = "0,1";
    startPop.value = "0";
    endPop.value = "1";
    console.log("ifPop", form.value.spilt)
  }
}

const handleAllCircle = async () => {
  ifAllCircle.value = !ifAllCircle.value;
  if (ifAllCircle.value) {
    const res = await getLsc(dataId.value);
    form.value.maxRul = res.data.runCircles;
  }
}

const getDataInfo = async () => {
  dataId.value = String(localStorage.getItem("dataId"));
  const res = await getLsc(dataId.value);
  if (res.code === 200) {
    const dataType = lsc_data_type.value.find((item: any) => {
      return item.value === res.data.dataType;
    }).label;
    dataSelect.value = res.data.dataName + "（类型：" + dataType + "）";
  }
}
const lscFormRef = ref<ElFormInstance>();
/** 提交按钮 */
const submitForm = async () => {
  if (form.value.spilt === "") {
    form.value.spilt = startPop.value + ',' + endPop.value;
  }
  lscFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      if (form.value.id) {
        await updateLsc(form.value).then(() => {
          updateStatus(Object.assign({
            id: dataId.value,
            status: 1,
          }))
        }).catch(e => {
          updateStatus(Object.assign({
            id: dataId.value,
            status: 2,
          }))
        });
      } else {
        await addLsc(form.value).then(() => {
          updateStatus(Object.assign({
            id: dataId.value,
            status: 1,
          }))
        }).catch(e => {
          updateStatus(Object.assign({
            id: dataId.value,
            status: 2,
          }))
        });
      }
      proxy?.$modal.msgSuccess("配置完成，开始预处理");
      startProcessing();
    }
  });
}
</script>

<style scoped lang="scss">
/* 样式 */
.my-box {
  width: 100%;
  height: 100%;
  background-color: #1ab394;
  padding: 10px
}
.my-form {
  width: 100%;
  height: 100%;
  background-color: #FFFFFF;
  padding: 20px;
  border-radius: 10px;
}
.item{
  max-width: 1000px;
}
.progress-container {
  margin-top: 20px;
  display: flex;
  align-items: center;
  color: rgb(96,98,102);
  font-weight: bold;
}
</style>
